import 'dart:async';

import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart' as sqflite_ffi;
import 'package:FiduMart/constants/constants.dart';
import 'package:FiduMart/core/db/account.dart';
import 'package:FiduMart/core/utils/logger.dart';

// https://github.com/tekartik/sqflite/blob/master/sqflite/doc/supported_types.md
class SqliteDB {
  static String tbAccount = "acc";

  static late Database db;

  late AccountDB account;
  SqliteDB() {}

  Future<void> init() async {
    WidgetsFlutterBinding.ensureInitialized();
    if (GetPlatform.isWindows) {
      sqflite_ffi.sqfliteFfiInit();
      databaseFactory = sqflite_ffi.databaseFactoryFfi;
    }

    var databasesPath = await getDatabasesPath();
    var sqlitedbName = getSqliteName();
    String path = join(databasesPath, sqlitedbName);
    db = await openDatabase(path, version: sqlitedbVersion, onCreate: _onCreate, onUpgrade: _onUpgrade);
    account = AccountDB();

    // 显示数据
    // await showData();
    // if (this.db == null) {
    //
    // }
    // return this.db!;
  }

  // ///如果指定了[version]，则[onCreate]、[onUpgrade]和[onDowngrade]可以
  // ///被调用。这些函数是互斥的——只有其中一个可以
  void _onCreate(Database db, int v) async {
    Logger.log("[db]onCreate, Databse initialized,$v");
    await initTable(db);
  }

  // 版本升级更新内容,版本升级变动只会运行一次，但是如果新安装的则不会执行到这里，不可用。
  void _onUpgrade(Database db, int oldVersion, int newVersion) async {
    Logger.log("[db]onUpgrade == oldVersion: $oldVersion,newVersion:$newVersion");
  }
  // onDowngrade版本降级

  Database getDB() {
    return db;
  }

  Future<bool> UpdateTable() async {
    return false;
  }

  // Future<bool> getOne(String where,) async {
  //   return false;
  // }

  Future<bool> hasTable() async {
    String sql = "SELECT name FROM sqlite_master WHERE type='table' AND name='info'";
    final tables = await getDB().rawQuery(sql);
    return tables.isNotEmpty;
  }

  Future<void> showData() async {
    List<Map> res4 = await getDB().rawQuery("select * from acc limit 0,15");
    Logger.log("dbname:${getSqliteName()},db version :$sqlitedbVersion");
    Logger.log("---------sqlite acc----------");
    Logger.log(res4);
    // Logger.log(res8);
    Logger.log("----------sqlite end---------");
  }

  // {"id":1,"mnepwd":"mnepwd","mne":"mne","userpwd":"userpwd"}
  Future<bool> initTable(Database db) async {
    // if (await hasTable()) {
    //   return true;
    // }
    Logger.log("[db]initTable start");
    // String path = await getDatabasesPath(); // /data/user/0/com.example.wpage/databases

    // {"id":1,"cid":1,"addr":"addr","pub":"pub","pri":"pri","coin":"coin","addrindex":1,"path":"path","name":"name","network":"network"}
    // typ 类型，1本地生成的钱包，2，导入钱包
    const String tbAccountSql = """
    create table if not exists acc(
    id INTEGER primary key AUTOINCREMENT,
    wid INTEGER  NOT NULL,
    nid INT NOT NULL,
    mainnid INT NOT NULL,
    name VARCHAR(20) NOT NULL,
    addr VARCHAR(100) NOT NULL,
    symbol VARCHAR(20) NOT NULL, 
    addrType INT NOT NULL,
    i INTEGER  NOT NULL
    );
    """;

    await db.execute(tbAccountSql);
    return true;
  }
}
